package com.zm.xiaohashu.auth.sercice.impl;

import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.RandomUtil;
import com.zm.exception.BizException;
import com.zm.response.Response;
import com.zm.xiaohashu.auth.constant.RedisKeyConstants;
import com.zm.xiaohashu.auth.enums.ResponseCodeEnum;
import com.zm.xiaohashu.auth.model.vo.verificationcode.SendVerificationCodeReqVO;
import com.zm.xiaohashu.auth.sercice.VerificationCodeService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class VerificationCodeServiceImpl implements VerificationCodeService {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public Response<?> send(SendVerificationCodeReqVO sendVerificationCodeReqVO) {
        String phone = sendVerificationCodeReqVO.getPhone();
        if (!PhoneUtil.isPhone(phone)) {
            throw new BizException(ResponseCodeEnum.PHONE_FORMAT_ERROR);
        }
        String key = RedisKeyConstants.buildVerificationCodeKey(phone);
        if (redisTemplate.hasKey(key)) {
            throw new BizException(ResponseCodeEnum.VERIFICATION_CODE_SEND_FREQUENTLY);
        }
        //生成验证码
        String verificationCode = RandomUtil.randomNumbers(6);
        log.info("==> 手机号: {}, 已发送验证码：【{}】", phone, verificationCode);

        // 存储验证码到 redis, 并设置过期时间为 3 分钟
        redisTemplate.opsForValue().set(key, verificationCode, 3, TimeUnit.MINUTES);
        return Response.success();
    }
}
